package cn.tannn.surenessdemo.sureness.subject;

import cn.tannn.surenessdemo.constant.HeaderConstant;
import com.usthe.sureness.subject.Subject;
import com.usthe.sureness.subject.SubjectCreate;
import com.usthe.sureness.subject.support.JwtSubject;

import javax.servlet.http.HttpServletRequest;

/**
 * 创建登录验证的方式: 请求头中拿去token值
 * eg:  token in header
 * header {
 *     "token" : token
 * }
 * @author tomsun28
 * @date 22:59 2020-03-02
 */
public class CustomHeaderTokenSubjectCreator implements SubjectCreate {



    @Override
    public boolean canSupportSubject(Object context) {
        // 判断 header 中 token是否存在
        if (context instanceof HttpServletRequest) {
            String token = ((HttpServletRequest)context).getHeader(HeaderConstant.HEADER_TOKEN);
            return token != null;
        } else {
            return false;
        }
    }

    @Override
    public Subject createSubject(Object context) {
        // create PasswordSubject from request
        String token = ((HttpServletRequest)context).getHeader(HeaderConstant.HEADER_TOKEN);

        String remoteHost = ((HttpServletRequest) context).getRemoteHost();
        String requestUri = ((HttpServletRequest) context).getRequestURI();
        String requestType = ((HttpServletRequest) context).getMethod();
        String targetUri = requestUri.concat("===").concat(requestType).toLowerCase();
        return JwtSubject.builder(token)
                .setRemoteHost(remoteHost)
                // 设置当前请求的资源格式，用于查询权限
                .setTargetResource(targetUri)
                .build();
    }
}
